package com.es;

import java.sql.*;
import java.util.HashMap;
import java.util.Properties;

/**
 * 写了一个工具类
 */
public class JDBCUtils {

    private static final String CONFIG_FILE_NAME = "jdbc.xml";

    private static  HashMap<String, Properties> envirments = new HashMap<>();

    static{
        envirments = JDBCConfigParser.parse(CONFIG_FILE_NAME);
    }

    public static Connection getConnection(String dbName){
        //
        if(envirments.isEmpty()){
            throw new RuntimeException("对不起，没有读取到任何的配置信息，请假查是否正确配置");
        }

        Properties properties = envirments.get(dbName);
        if(properties==null || properties.isEmpty()){
            throw new RuntimeException("没有读取到对应的配置信息for:【"+dbName+"】");
        }

        try {
            Class.forName(properties.getProperty("driverClassName"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            Connection connection = DriverManager.getConnection(properties.getProperty("url"),properties);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 释放资源的方法
     * @param connection
     * @param statement
     * @param resultSet
     */
    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                if(statement != null){
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }finally {
                        if(resultSet != null){
                            try {
                                resultSet.close();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}
